//
//  ModelController.m
//  TextRead
//
//  Created by 奇阅科技 on 14-11-20.
//  Copyright (c) 2014年 奇阅科技. All rights reserved.
//

#import "ModelController.h"
#import "ReadPageViewController.h"
#import "ZMYReadPageViewController.h"
#import "Config.h"
#import "ReadConfig.h"
#import "ZMYReadViewController.h"
#import "SIDownloadManager.h"
#import "SIBreakpointsDownload.h"
#import "BookReadPermissions.h"
#import "PayWebView.h"
#import "DefaultSubscription.h"
#import "HeadViewController.h"
#import "FootViewController.h"
@interface ModelController ()<ReadPageTextViewDelegate,PayWebViewDelegate>
{
    BookChapterText *chapterText;
}
@property (nonatomic,strong)BookChapterInfo *bookChapterInfo;
@end

@implementation ModelController

- (instancetype)init {
    self = [super init];
    if (self) {
        // Create the data model.
        
    }
    return self;
}
-(void)parseBookChapterText{
    _currentPageData = [[NSMutableArray alloc]init];
    if (self.delegate) {
        [self parseBookChapterText:self.delegate.currentChapterInfo];
//        self.beforeChapterInfo = self.delegate.beforeChapterInfo;
//        self.nextChapterInfo = self.delegate.nextChapterInfo;
    }
}
-(void)parseBookChapterText:(BookChapterInfo *)bookChapterInfo{
    self.bookChapterInfo = bookChapterInfo;
    chapterText = [[ZMYLKDB getLKDBHelper]getBookChapterTextWithArticleid:self.book.articleid chapterId:bookChapterInfo.chapterId];
    if (!chapterText) {
        return;
    }
    _currentPageData = [NSMutableArray new];
    // 文本容器
    NSTextStorage *storage = [[NSTextStorage alloc] initWithString:chapterText.chapterTextString];
    // 文本容器的布局管理器
    NSLayoutManager *layoutManager = [NSLayoutManager new];
    [storage addLayoutManager:layoutManager];
    // 段落属性
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineHeightMultiple  = 1.3f;                    // 可变行高,乘因数
    paragraphStyle.lineSpacing         = 1.0f;                    // 行间距
    paragraphStyle.paragraphSpacing    = 1.f;                   // 段间距
    paragraphStyle.alignment           = NSTextAlignmentLeft;    // 对齐方式
    paragraphStyle.tailIndent          = SCREEN_WIDTH-30;                    // 文本宽度
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
    [storage addAttribute:NSParagraphStyleAttributeName
                    value:paragraphStyle
                    range:NSMakeRange(0, storage.string.length)];
    // 字体属性
    [storage addAttribute:NSFontAttributeName
                    value:[UIFont systemFontOfSize:[ReadConfig currentAccount].foutSize]
                    range:NSMakeRange(0, storage.string.length)];
    
    [storage addAttribute:NSForegroundColorAttributeName
                    value:[ReadConfig currentAccount].textColor
                    range:NSMakeRange(0, storage.string.length)];
    // 分段显示文本容器中的内容
    CGSize textFrame = CGSizeMake(SCREEN_WIDTH-30, SCREEN_HEIGHT-80);
    NSTextContainer *textContainer1 = [[NSTextContainer alloc] initWithSize:textFrame];
    [layoutManager addTextContainer:textContainer1];
    NSRange ss = [layoutManager glyphRangeForTextContainer:textContainer1];
    [_currentPageData addObject:NSStringFromRange(ss)];
    while (ss.location+ss.length<storage.string.length) {
        NSTextContainer *textContainer2 = [[NSTextContainer alloc] initWithSize:textFrame];
        [layoutManager addTextContainer:textContainer2];
        ss = [layoutManager glyphRangeForTextContainer:textContainer2];
        [_currentPageData addObject:NSStringFromRange(ss)];
    }
    [_currentPageData insertObject:@"Header" atIndex:0];
    [_currentPageData addObject:@"Footer"];
}
-(void)downLoadNextChapter:(BookChapterInfo *)nextChapterInfo{
    if (nextChapterInfo) {
        BookChapterText *nextChapterText = [[ZMYLKDB getLKDBHelper]getBookChapterTextWithArticleid:self.book.articleid chapterId:nextChapterInfo.chapterId];
        if (!nextChapterText) {
            __weak typeof(self) weakSlef = self;
            __block MBProgressHUD *progressHud = [MBProgressHUD showHUDAddedTo:[AppDelegate delegate].window animated:YES];
            progressHud.removeFromSuperViewOnHide = YES;
            progressHud.dimBackground = YES;
            progressHud.mode =MBProgressHUDModeDeterminate;
            progressHud.detailsLabelText = @"加载中...";
            [progressHud setProgress:0.1];
            progressHud.removeFromSuperViewOnHide=YES;
            NSString *purviewMark = [[NSString stringWithFormat:@"%@%@",nextChapterInfo.chapterId,nextChapterInfo.chapterId] md5];
            purviewMark = [[NSString stringWithFormat:@"qy_%@",purviewMark] md5];
            NSString *currentAppVersion = [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"];
            NSString *urlStr = [NSString stringWithFormat:@"http://%@/web/qy_book.php?a=download_articleid&purviewMark=%@&chapterids=%@&output=txt&ct=iOS&v=%@&srcid=iOS",SERVER,purviewMark,nextChapterInfo.chapterId,currentAppVersion];
            NSString *downloadPath = [[PathHelper cacheDirectoryPathWithName:@"Lib"]stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@%@",self.book.articleid,nextChapterInfo.chapterId,nextChapterInfo.chapterId]];
            SIDownloadManager *siDownloadManager = [SIDownloadManager sharedSIDownloadManager];
            [siDownloadManager  addDownloadFileTaskInQueue:urlStr toFilePath:downloadPath breakpointResume:YES rewriteFile:NO DidComplete:^(SIDownloadManager *siDownloadManager, SIBreakpointsDownload *paramOperation) {
                if ([paramOperation.downloadFilePath isEqualToString:downloadPath]) {
                    if ([[ZMYLKDB getLKDBHelper]unarchiveFreeChapter:downloadPath Book:weakSlef.book]) {
                        progressHud.progress = 1;
                        [progressHud setHidden:YES];
                    }else{
                        progressHud.progress = 1;
                        [progressHud setHidden:YES];
                        [AppDelegate showHUDAndHide:@"章节下载失败" view:[AppDelegate delegate].window];
                    }
                }
            } Progress:^(SIDownloadManager *siDownloadManager, SIBreakpointsDownload *paramOperation, double paramProgress) {
                if ([paramOperation.downloadFilePath isEqualToString:downloadPath]) {
                    progressHud.progress = paramProgress;
                }
            } Error:^(SIDownloadManager *siDownloadManager, SIBreakpointsDownload *paramOperation, NSError *paramError) {
                if ([paramOperation.downloadFilePath isEqualToString:downloadPath]) {
                    NSLog(@"%@ withError:%@",paramOperation.url,paramError.localizedDescription);
                    progressHud.progress = 0;
                    [progressHud setHidden:YES];
                    [AppDelegate showHUDAndHide:paramError.localizedDescription view:[AppDelegate delegate].window];
                }
                
            }];
        }
    }
}
-(NSInteger)getIndexItem:(NSRange)rang{
    for (NSString *srang in self.currentPageData) {
        NSRange mrang = NSRangeFromString(srang);
        if (NSIntersectionRange(mrang, rang).length>0) {
            return [self.currentPageData indexOfObject:srang];
        }
    }
    return 1;
}
- (ReadPageViewController *)viewControllerAtIndex:(NSUInteger)index storyboard:(UIStoryboard *)storyboard {
    
    // Return the data view controller for the given index.
    if (([self.currentPageData count] == 0) || (index >= [self.currentPageData count])) {
        return nil;
    }
    if (index==0) {
        HeadViewController *dataViewController = [[HeadViewController alloc]init];
        dataViewController.indexItem = index;
        dataViewController.allItemNum = self.currentPageData.count-2;
        dataViewController.book = self.book;
        return dataViewController;
    } else if(index==self.currentPageData.count-1) {
        FootViewController *dataViewController = [[FootViewController alloc]init];
        dataViewController.indexItem = index;
        dataViewController.allItemNum = self.currentPageData.count-2;
        dataViewController.book = self.book;
        return dataViewController;
    }else{
        ZMYReadPageViewController *dataViewController = [storyboard instantiateViewControllerWithIdentifier:@"ZMYReadPageViewController"];
        NSString *sr = self.currentPageData[index];
        ReadSchedule *readSch = [ReadSchedule new];
        readSch.articleid = self.book.articleid;
        readSch.chapterId = self.bookChapterInfo.chapterId;
        readSch.rang = sr;
        [[ZMYLKDB getLKDBHelper]updateReadSchedule:readSch];
        if ([self.delegate respondsToSelector:@selector(updateBookmarkImage:)]) {
            [self.delegate updateBookmarkImage:sr];
        }
        NSRange rang = NSRangeFromString(sr);
        dataViewController.indexItem = index-1;
        dataViewController.allItemNum = self.currentPageData.count-2;
        dataViewController.readSchedule = readSch;
        dataViewController.textObject = [chapterText.chapterTextString substringWithRange:rang];
        dataViewController.delegate = self.delegate;
        dataViewController.book = self.book;
        dataViewController.bookChapterInfo = self.bookChapterInfo;
        return dataViewController;
    }
}

- (NSUInteger)indexOfViewController:(ReadPageViewController *)viewController {
    if (![viewController.readSchedule.chapterId isEqualToString:self.bookChapterInfo.chapterId]) {
        NSMutableArray *chapterArray = [NSKeyedUnarchiver unarchiveObjectWithFile:[[PathHelper documentDirectoryPathWithName:@"db"]
                                                                                   stringByAppendingPathComponent:[NSString stringWithFormat:@"%@ChapterInfo",self.book.articleid]]];

            for (BookChapterInfo *chapterInfo in chapterArray) {
                if ([chapterInfo.chapterId isEqualToString:viewController.readSchedule.chapterId]) {
                    [self parseBookChapterText:chapterInfo];
                    break;
                }
        }
    }
    return viewController.indexItem+1;
}


- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController
{
    NSUInteger index = [self indexOfViewController:(ReadPageViewController *)viewController];
//    if (index == 0&&!self.delegate.beforeChapterInfo) {
//        return nil;
//    }
//    if (self.delegate.beforeChapterInfo) {
//        if (index == 0) {
//            _currentPageData = [[NSMutableArray alloc]init];
//            [self parseBookChapterText:self.delegate.beforeChapterInfo];
//            index = _currentPageData.count-1;
//        }else{
//            index--;
//        }
//    } else {
//        index--;
//        if (index <= [self.currentPageData count]-1) {
//            BookReadPermissions *readPer = [BookReadPermissions new];
//            readPer.articleid = self.book.articleid;
//            readPer.chapterId = self.delegate.beforeChapterInfo.chapterId;
//            if (![readPer getMyReadPermissions]) {
//                [self getMyReadPermissions];
//            }
//        }
//    }
    index--;
    [self.delegate changePageSlile];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"HidenReadNav" object:nil];
    return [self viewControllerAtIndex:index storyboard:viewController.storyboard];
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController
{
    NSUInteger index = [self indexOfViewController:(ReadPageViewController *)viewController];
//    if (index == NSNotFound) {
//        return nil;
//    }
//    if (self.delegate.nextChapterInfo) {
//        if (index >= [self.currentPageData count]-1) {
//            _currentPageData = [[NSMutableArray alloc]init];
//            [self parseBookChapterText:self.delegate.nextChapterInfo];
//            index = 0;
//        }else{
//            index++;
//        }
//    } else {
//        if (index >= [self.currentPageData count]-1) {
//            return nil;
//        }
//        index++;
//    }
//    BookReadPermissions *readPer = [BookReadPermissions new];
//    readPer.articleid = self.book.articleid;
//    readPer.chapterId = self.bookChapterInfo.chapterId;
//    if (![readPer getMyReadPermissions]) {
//        [self getMyReadPermissions];
//    }
    index++;
    [self.delegate changePageSlile];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"HidenReadNav" object:nil];
    return [self viewControllerAtIndex:index storyboard:viewController.storyboard];
}
-(void)getMyReadPermissions{
    //请求服务器阅读权限
    [[ZMYNetWorkAPI default]getDownloadChapterPermission:self.bookChapterInfo.chapterId Book:self.book Response:^(NSDictionary *resultDic) {
        NSInteger ret = [[resultDic objectForKey:@"ret"] integerValue];
        switch (ret) {
            case 200:{//可以阅读
                BookReadPermissions *readPer = [BookReadPermissions new];
                readPer.articleid = self.book.articleid;
                readPer.chapterId = self.bookChapterInfo.chapterId;
                readPer.readPermissions = YES;
                [readPer updateBookReadPermissions];
                break;
            }
                
            case 1:{
                [AppDelegate showwarnHUDAndHide:@"章节扣费失败，请登录后继续操作" view:[AppDelegate delegate].window];
                break;
            }
                
            case 203:{//章节未订阅
                [self chargeForChapters:self.bookChapterInfo.chapterId];
                break;
            }
            default:{
                [AppDelegate showAlert:nil message:@"网络请求失败，请稍后再试"];
                break;
            }
                break;
        }
    } error:^(NSString *errorStr) {
        [AppDelegate showAlert:nil message:errorStr];
        [self cancel];
    }];
}
#pragma mark 章节扣费
-(void)chargeForChapters:(NSString *)autosub_chapters{
    UserAccount *user = [UserAccount currentAccount];
    if (!user) {
        [AppDelegate showwarnHUDAndHide:@"请登录后继续操作" view:[AppDelegate delegate].window];
        return;
    }
    if (user.auto_subscription) {
        //如果是自动订阅，就去申请扣费
        [[ZMYNetWorkAPI default]getDownloadChargeForChapters:autosub_chapters Book:self.book Response:^(NSDictionary *resultDic) {
            NSInteger ret = [[resultDic objectForKey:@"ret"] integerValue];
            switch (ret) {
                case 200:{//可以下载
                    BookReadPermissions *readPer = [BookReadPermissions new];
                    readPer.articleid = self.book.articleid;
                    readPer.chapterId = self.bookChapterInfo.chapterId;
                    readPer.readPermissions = YES;
                    [readPer updateBookReadPermissions];
                    break;
                }
                case 1:{
                    [AppDelegate showwarnHUDAndHide:@"章节扣费失败，请登录后继续操作" view:[AppDelegate delegate].window];
                    break;
                }
                case 202:{//余额不够
                    [[ZMYNetWorkAPI default]cancelAllPermissionNetworkOperation];
                    [[ZMYNetWorkAPI default]cancelAllChargeNetworkOperation];
                    [self showWebView:autosub_chapters];
                    break;
                }
                default:{
                    [AppDelegate showAlert:nil message:@"网络请求失败，请稍后再试"];
                    break;
                }
                    break;
            }
            
        } error:^(NSString *errorStr) {
            [AppDelegate showAlert:nil message:errorStr];
            [self cancel];
        }];
    } else {
        //如果不是自动订阅，就去申请扣费
        [[ZMYNetWorkAPI default]cancelAllPermissionNetworkOperation];
        [[ZMYNetWorkAPI default]cancelAllChargeNetworkOperation];
        [self showWebView:autosub_chapters];
        return;
    }
}
-(void)showWebView:(NSString *)textIDs{
    
    UserAccount *user = [UserAccount currentAccount];
    PayWebView *view = [[[NSBundle mainBundle]loadNibNamed:@"PayWebView" owner:self options:nil] lastObject];
    //md5(md5（用户ID.时间戳.加密密匙).加密密匙)
    NSString *time = [NSString stringWithFormat:@"%.f",[ZMYNetWorkAPI currentTime]];
    NSString *auth = [[[NSString stringWithFormat:@"%@%@",[[NSString stringWithFormat:@"%@%@%@",user.uid,time,PRIVATE_KEY] md5],PRIVATE_KEY] md5] substringToIndex:10];
    NSString *currentAppVersion = [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"];
    
    view.delegate = self;
    //dataapi.yuewen.cc/web//qy_book.php?a=sub_multiple_order&uid=85623598&token=062dd8cb06&auth=3845c90368&t=1419941301004&articleid=1056&textid=27888&srcid=anzhi&v=20&pt=client&ct=android
    view.webUrl = [NSString stringWithFormat:@"http://%@/web/qy_book.php?a=sub_multiple_order&textid=%@&articleid=%@&v=%@&uid=%@&token=%@&t=%@&auth=%@&srcid=iOS&ct=iOS&pay_way=iOS&pt=client",SERVER,textIDs,self.book.articleid,currentAppVersion,user.uid,user.token,time,auth];
    [view showView];
}
-(void)cancel{
    BookReadPermissions *readPer = [BookReadPermissions new];
    if (self.book) {
        readPer.articleid = self.book.articleid;
        readPer.chapterId = self.bookChapterInfo.chapterId;
        if (![readPer getMyReadPermissions]) {
            [self.delegate backActionForNavigation:nil];
        }
    }
}
@end
